#-*- coding: utf-8 -*-

import string
import md5
import datetime 
import urllib
from favshop.constant import *
from favshop.utils import *
from django.utils import simplejson
from google.appengine.api import urlfetch

logging.getLogger().setLevel(logging.INFO)

def taobao_items_get(**kwargs):
    kwargs['sip_apiname'] = 'taobao.items.get'
    return isv_general(kwargs)

def alisoft_validateUser(**kwargs):
    kwargs['sip_apiname'] = 'alisoft.validateUser'
    return isv_general(kwargs)

def taobao_shop_get(**kwargs):
    kwargs['sip_apiname'] = 'taobao.shop.get'
    return isv_general(kwargs)

def taobao_user_get(**kwargs):
    kwargs['sip_apiname'] = 'taobao.user.get'
    return isv_general(kwargs)

def decrator_isv_general(func):
    '''
    Decrator of isv_general
    Deal with SIP response, if get the right response then return JSON object.
    Otherwise, return None.
    '''
    def new_func(*args, **kwargs):
        result = func(*args, **kwargs)
        try:
#            logging.info(result)
            ret_obj = simplejson.loads(result)
        except ValueError:
            logging.warning(result)
            return None
        if ret_obj.has_key('error_rsp'):
            logging.warning(result)
            return None
        else: # get normal result
            return ret_obj
    return new_func

@decrator_isv_general
def isv_general(context):
    # context is a dict, which collects necessary parameters
    context['sip_timestamp'] = \
        (datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')
    context['sip_appkey'] = SIP_APPKEY
    context['format'] = 'json'
    context['v'] = '1.0'
    
    # generate signature
    context['sip_sign'] = sign(SECRET_KEY, context)
    
    # generate URL payload
    deal_with_item = lambda item:item[0]+'='+urllib.quote(item[1])
    payload = '&'.join(deal_with_item(item) for item in context.items())
    if B_PRODUCTION:
        url = SIP_PRODUCTION_URL_PRE + payload
    else:
        url = SIP_SANDBOX_URL_PRE + payload
    
    # fetch data from SIP
    try:
        result = urlfetch.fetch(url)
        if result.status_code == 200:
            return result.content
        else:
            logging.warning('urlfetch error, status code:%d', result.status_code)
    except urlfetch.InvalidURLError:
        logging.warning('urlfetch InvalidURLError, url: %s', url)
    except urlfetch.DownloadError:
        logging.warning('urlfetch DownloadError, url: %s', url)
        
    return ''

def sign(secretkey, context):
    '''compute sign for Alisoft platform
    Param:
    secretkey   app key. e.g. 6fa62020daef11ddaf54eb4b8fdea865
    context     parameter list
    
    Return:
    return MD5 string
    '''
    item_list = sorted(context.items(), key=lambda d:d[0]) # sort
    deal_with_item = lambda i: i[0]+i[1] # return param=value
    m = md5.new()
    m.update(secretkey+''.join(deal_with_item(item) for item in item_list))
    return string.upper(m.hexdigest())

if __name__ == '__main__':
    # compute sign
    context = {}
    context['sip_timestamp'] = '2009-01-21 21:43:39'
    context['sip_appkey'] = '20629'
    context['userId'] = '14876669'
    context['appInstanceId'] = 'USERCA0502660FC0A68C98E449FE2951ED4C'
    context['token'] = 'E1CB71AFBE99711767017336B894F1B69D7629570AE6EE6603D188993F29621D848EA806C9E554557273D98035FEE61C'
    context['sip_apiname'] = 'alisoft.validateUser'
    context['format'] = 'xml'
    context['sip_sessionid'] = 'cba055806e1546b58a9df1beae0c8418'
    secretkey = '6fa62020daef11ddaf54eb4b8fdea865'
    print sign(secretkey, context)